package com.cat.slidingWindow;

import java.util.HashMap;

/**
 * @author cat
 * @description https://leetcode.cn/problems/count-the-number-of-good-subarrays/
 * @create 2025/7/31 09:31
 * @since JDK17
 */

public class Solution17 {
    static HashMap<Integer, Integer> map = new HashMap<>();
    public long countGood(int[] nums, int k) {
        long ans = 0;
        int n = nums.length, cnt = 0, total;
        map.clear();
        for (int l = 0, r = 0; r < n; r++) {
            while (r < n && cnt < k) {  //
                total = map.getOrDefault(nums[r], 0);
                if (total >= 1) cnt += total;
                map.put(nums[r++], total + 1);
            }
            while (cnt >= k) {
                total = map.get(nums[l]) - 1;
                if (total >= 1) cnt -= total;
                map.put(nums[l++], total);
                ans += n - r + 1;
            }
        }

        return ans;
    }
}
